package com.zzl.car.util;

import lombok.Getter;
import lombok.Setter;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Getter
@Setter
@Component
@ConfigurationProperties(prefix="drivinglicense")
public class ZdpDrivingLicense {
    @Autowired
    private RedisTemplate redisTemplate;
    private String clientId ="clientId";
    private String clientSecret ="clientSecret";

    // 进行识别
    /*
    * imgParam: 图片文件的base64字符串转成url
    * */
    public String drivingLicense(String imgParam){
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license";
        try {

            String param = "image=" + imgParam;

            // 获取到后，可以存入缓存
            String accessToken = (String)redisTemplate.opsForValue().get("accessToken");
            if(accessToken==null){
                accessToken = getAuth();
                // 存入缓存，设置过期日期，半个月
                redisTemplate.opsForValue().set("accessToken",accessToken,15, TimeUnit.DAYS);
            }

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println("识别后，获取到数据");
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public  String getAuth(){
        return getAuth(clientId,clientSecret);
    }

    public String getAuth(String ak,String sk){
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            System.out.println("驾驶证识别，获取toke");
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             * {
             *   "refresh_token": "25.b55fe1d287227ca97aab219bb249b8ab.315360000.1798284651.282335-8574074",
             *   "expires_in": 2592000,
             *   "scope": "public wise_adapt",
             *   "session_key": "9mzdDZXu3dENdFZQurfg0Vz8slgSgvvOAUebNFzyzcpQ5EnbxbF+hfG9DQkpUVQdh4p6HbQcAiz5RmuBAja1JJGgIdJI",
             *   "access_token": "24.6c5e1ff107f0e8bcef8c46d3424a0e78.2592000.1485516651.282335-8574074",
             *   "session_secret": "dfac94a3489fe9fca7c3221cbf7525ff"
             * }
             */
            System.out.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.out.printf("获取token失败！");
            e.printStackTrace();
        }
        return null;
    }

}

